<template>
  <div class="login-container">
    <el-card class="login-card" shadow="never">
      <h2 class="login-title">管理员登录</h2>
      <el-form :model="form" ref="form" label-width="100px" @submit.native.prevent="handleLogin">
        <el-form-item label="用户名" :rules="usernameRules">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" :rules="passwordRules">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btn" type="primary" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import baseUrl from '../assets/path.js';
import axios from 'axios';
export default {
  data() {
    return {
      baseUrl,
      form: {
        username: '',
        password: '',
      },
      usernameRules: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      passwordRules: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
    };
  },
  methods: {
    handleLogin() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 使用 axios 发送 POST 请求
          axios.post(`${this.baseUrl}/admin/login`, this.form)
            .then((response) => {
              // 登录成功的处理
              Message.success({
                message: '登录成功',
                duration: 1500 // 设置为 1.5 秒
              });
              this.$router.push('/home');
              console.log('登录成功:', response.data);
            })
            .catch((error) => {
              // 处理错误，例如显示错误消息
              if (error.response) {
                Message.error(error.response.data.message || '登录失败，请重试');
              } else {
                Message.error('登录请求出错，请检查网络连接');
              }
            });
        } else {
          // 如果验证失败，使用 Message 弹出提示
          Message.error('请检查输入是否完整');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 85vh;
  background-image: url('@/assets/background.jpg'); /* 设置背景图 */
  background-size: cover; /* 使背景图覆盖整个容器 */
  background-position: center; /* 背景图居中 */
}

.login-card {
  width: 450px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  border-radius: 4px; /* 圆角 */
}

.btn {
  width: 75%;
  margin-right: 100px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}
</style>
